<?php
namespace Home\Controller;
use Think\Controller;
/*
 ×商品管理控制器
 ×
 */
 class ItemController extends HomeController {
    public function index()
    {
        
        $item=D('Item');
        $arg['page']=I('get.page',1,'strip_tags');
        $arg['typeid']=!empty($_GET['typeid'])?$_GET['typeid']:'';
        $arg['brandid']=!empty($_GET['brandid'])?$_GET['brandid']:'';
        $arg['platid']=1;//默认显示平台产品；
        $arg['keywords']=!empty($_GET['keywords'])?base64_decode($_GET['keywords']):'';
      
        $result=$item->index($arg);
         /*顶级类目**/
        $toptype=M('type')->where("pid=0")->getField("typeid,typename");
       $this->assign('toptype',$toptype);
        $this->assign('items',$result['item']);
        $this->assign('pagearr',$result['pagearr']);

        $this->display('index');
    }
    /*
     *添加商品
     */
    public function addItem()
    {
        $typeid=I('get.typeid','','strip_tags');
        //获取所有类目
        $type=new \Home\Controller\TypeController();
        $typearr=$type->getListCat();

        /*顶级类目**/
        $toptype=M('type')->where("pid=0")->getField("typeid,typename");
       $this->assign('toptype',$toptype);


        //如果typeid非空需要选择商品属性
        if(!empty($typeid))
        {
        
            //获取所有的品牌
            $brands=M('brand')->getField('brandname',true);
            $temp_brand=array();
            foreach ($brands  as $key => $value) {
                $temp_brand[$key]['label']=$value;
                $temp_brand[$key]['value']=$value;
            }

         //获取总后台下所有供货商
         $suppliers=M('supper_user')->where('adminid !=0')->order('supperid desc')->getField('supperid,contactname');

        //获取该类目下的所有属性
            $typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
            ->where('a.typeid=%d',$typeid)
            ->getField('b.propertyid,a.typeid,a.typename,b.propertyname');

            if(!empty($typeproperty))
            {
                foreach($typeproperty as $key=>&$value)
                {
                    $where['propertyid']=$key;
                    $value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
                    ->where('a.propertyid=%d',$where['propertyid'])
                    ->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
                }

            }
        
        

         
         $this->assign('suppliers',$suppliers);
         $this->assign('typearr',$typearr);//分类树
         $this->assign('typeproperty',$typeproperty);
         $this->assign('brands',json_encode($temp_brand,JSON_UNESCAPED_UNICODE));
         

         $this->assign('typeid',$typeid);
         $this->display('pro_spec');

        }else{

            $this->assign('typearr',$typearr);//分类树
            $this->display();
        }

    }
    //保存商品
    public function saveItem()
    {
    //获取商品基本 信息
    $data['areatype']=!empty($_POST['areatype'])?$_POST['areatype']:2;
    /*$data['status']=I('post.status','','strip_tags');*/
    $data['itemname']=I('post.itemname','','strip_tags');
    $data['bn']=I('post.bn','','strip_tags');
    $data['price']=!empty($_POST['price'])?$_POST['price']:0;
    $data['supperprice']=!empty($_POST['supperprice'])?$_POST['supperprice']:0;
    $data['supperid']=I('post.supperid',0,'strip_tags');//供货商ID
    $data['platid']=!empty($_SESSION['adminid'])?$_SESSION['adminid']:0;//总后台ID
    $data['inventory']=!empty($_POST['inventory'])?$_POST['inventory']:0;
    $data['typeid']=I('post.itemtype','','strip_tags');
    $data['createtime']=time();
    $data['examine']=1;

    ////通过品牌查找品牌id
    $brandname=I('post.brand','','strip_tags');
     $data['brandid']=M('brand')->where("brandname='%s'",$brandname)->getField("brandid");
     ////品牌和类目对应起来
     $typeid=M('type_brand')->where("brandid='%d' And typeid='%d'",$data['brandid'],$data['typeid'])->select();///检测该品牌是否有对应的类目

     if(empty($typeid))
     {
      $map['typeid']=I('post.itemtype','','strip_tags');
      $map['brandid']=$data['brandid'];
      M('type_brand')->add($map);   
  }
     
   

    $itemdescdata=!empty($_POST['editorValue'])?$_POST['editorValue']:'';
    //获取商品属性数组
    $property=I('post.proper','','strip_tags');
    //货品颜色
    $p_color=I('post.p_color','','strip_tags');
    //货品库存
    $p_inventory=I('post.p_inventory',0,'strip_tags');
    //货品价格
    $p_price=I('post.p_price',0,'strip_tags');
    $p_supprice=I('post.supper_price',0,'strip_tags');

    //调用上传图片
    if(!empty($_FILES['listimg']['tmp_name'])){
        $data['itemimg']=$this->uploadimg();

        if ($data['itemimg']==false)
        {
            $this->error('图片尺寸不符');
            //echo  "<script type='text/javascript'>alert('图片尺寸不符');window.history.go(-1);</script>";die;
        }
    }

    $item=M('item');
    //添加商品基本信息
    $itemid=$item->data($data)->add();
    if (!empty($itemid)) {
        $itemdesc=M('item_desc');
        $itemdesc->create();
        $itemdesc->itemid=$itemid;
        $itemdesc->itemdesc=$itemdescdata;
        $itemdesc->add();
    }
    //保存产品属性
    if(!empty($itemid)){

        if(!empty($property))
        {
            $item_property=M('item_property');
            $datalist=array();
            foreach($property as $key=>$value)
            {
                $datalist[]=array('itemid'=>$itemid,'propertyid'=>$key,'propertyvalueid'=>$value);
            }
        //批量保存商品属性
            $item_property->addAll($datalist);
        }
        //保存商品的颜色，库存，价格,供货价格
        $temp_product=array();

        if(!empty($p_price) && !empty($p_color) && !empty($p_inventory) &&!empty($p_supprice))
        {
            $product=M('product');
            $product->create();
            foreach ($p_price as $key => $value)
            {
                $product->itemid=$itemid;
                $product->inventory=$p_inventory[$key];
                $product->price=$p_price[$key];
                $product->color=$p_color[$key];
                $product->supprice=$p_supprice[$key];
                $result=$product->add();
            }
        }
    }

    if($itemid || $result)
    {
        //echo "<script type='text/javascript'>alert('添加商品成功');</script>";
        $this->success('添加产品成功');
    }else
    {
        $this->error('添加产品失败，请重新添加');
    }

    }
    

    /*
     *编辑产品
     *@param  itemid
     */
    public function editItem(){
        $itemid=I('get.itemid','','strip_tags');
        if(!$itemid) return false;
      //获取分类树
        $type=new \Home\Controller\TypeController();
        $typearr=$type->getListCat();
      //获取商品基本信息
        $item=M('item');
        $iteminfo=$item->where('itemid=%d',$itemid)->select();
        //获取所有品牌
        $brands=M('brand')->getField('brandid,brandname');

        //获取运营商或者总后台的供货商
        if( !empty($iteminfo[0]['yid'])){
             $suppliers=M('supper_user')->where('yid=%d',$iteminfo[0]['yid'])->order('supperid desc')->getField('supperid,contactname');
        }else{
             $suppliers=M('supper_user')->where('adminid !=0')->order('supperid desc')->getField('supperid,contactname');
        }
       
         //如果此商品存在颜色规格
        $products=array();
        $product=M('product');
        $productids=$product->where('itemid=%d',$itemid)->getField('productid',true);
        if(!empty($productids))
        {
            foreach($productids as $key=>$value)
            {
                $products[]=$product->where('productid=%d',$value)->getField('productid,inventory,price,color,supprice');
            }

        }

      //获取商品详情
        $detail=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');

      //获取该类目下的所有属性
        $typeproperty=M('type a')->join('inner join '. C('DB_PREFIX').'type_property b on a.typeid=b.typeid ')
        ->where('a.typeid=%d',$iteminfo[0]['typeid'])
        ->getField('b.propertyid,a.typeid,a.typename,b.propertyname');
        if(!empty($typeproperty))
        {
            foreach($typeproperty as $key=>&$value)
            {
                $where['propertyid']=$key;
                $value['select']=M('type_property a')->join('inner join '.C('DB_PREFIX').'type_propertyvalue b on a.propertyid=b.propertyid')
                ->where('a.propertyid=%d',$where['propertyid'])
                ->getField('b.valueid,a.propertyid,a.propertyname,b.propertyvalue ');
            }

        }
        //获取已选择的属性
        $seledpro=M('item_property')->where('itemid=%d',$iteminfo[0]['itemid'])->getField('propertyid,propertyvalueid');
        foreach($typeproperty as $key=>&$value)
        {

            foreach($value['select'] as $k=>&$v)
            {

                if($v['valueid']==$seledpro[$key])
                {

                    $v['selected']='true';
                }
            }
        }
        ///获取该商品的购物区
        $areatype=M('item')->where("itemid='%d'",$itemid)->getField("areatype");
        $this->assign('areatype',$areatype);
        $this->assign('suppliers',$suppliers);
        $this->assign('detail',$detail);
        $this->assign('typearr',$typearr);
        $this->assign('products',$products);
        $this->assign('iteminfo',$iteminfo[0]);
        $this->assign('brands',$brands);
        $this->assign('typeproperty',$typeproperty);
        $this->display('edititem');
    }


    //更新产品
    public function updateItem()
    {
        $data['areatype']=!empty($_POST['areatype'])?$_POST['areatype']:2;////购物区
        $data['activityid']=$_POST['activityid'];
        $data['discount']=$_POST['discount'];
        $data['modifietime']=time();
        $itemid=I('post.itemid','','strip_tags');
        $data['typeid']=I('post.typeid','','strip_tags');
        $data['itemname']=I('post.itemname','','strip_tags');
        $data['bn']=I('post.bn','','strip_tags');
        $data['brandid']=I('post.brand','','strip_tags');
        $data['price']=I('post.price','','strip_tags');
        $data['mkprice']=I('post.mkprice','','strip_tags');
        $data['inventory']=I('post.inventory','','strip_tags');
        $data['supperprice']=I('post.supperprice',0,'strip_tags'); //供货价
        $data['supperid']=I('post.supperid',0,'strip_tags');
        $data['examine']=1;
       
         
         //检测数据库是否存在这个品牌，和类目对应
        $typeid=M('type_brand')->where("brandid='%d'And typeid='%d'",$data['brandid'],$data['typeid'])->select();

        if(empty($typeid))
        {
            $map['typeid']=I('post.typeid','','strip_tags');
            $map['brandid']=I('post.brand','','strip_tags');
            M('type_brand')->add($map);
        }
         //商品详情
        $detail['itemdesc']=$_POST['editorValue'];
        $typeid=I('post.itemtype','','strip_tags');
        $proper=I('post.proper','','strip_tags');
         //调用上传图片

        if(!empty($_FILES['listimg']['tmp_name']))
        {
            $data['itemimg']=$this->uploadimg();

            if ($data['itemimg']==false)
            {
                $this->error('图片尺寸不符');
                   
            }
        }
            //更新基本信息
        $item=M('item');

        $result=$item->where('itemid=%d',$itemid)->save($data);


            //更新商品详情
        $ret=M('item_desc')->where('itemid=%d',$itemid)->getField('itemid');
        if(!$ret){
            $detail['itemid']=$itemid;
            M('item_desc')->add($detail);
        }else{

            M('item_desc')->where('itemid=%d',$itemid)->save($detail);
        }
            //更新属性
        $item_property=M('item_property');

        foreach($proper as $key=>$value)
        {
            $map['propertyvalueid']=$value;
            $tempres=$item_property->where('itemid=%d and propertyid=%d',$itemid,$key)->count();
            if(!empty($tempres)){
                $result=$item_property->where('itemid=%d and propertyid=%d',$itemid,$key)->save($map);
            }else{
                $map['itemid']=$itemid;
                $map['propertyid']=$key;
                $result=$item_property->add($map);
            }

        }
            //组合颜色、库存、价格
        $p_color=I('post.p_color','','strip_tags');
        $p_price=I('post.p_price',0,'strip_tags');
        $p_inventory=I('post.p_inventory',0,'strip_tags');
        $p_supprice=I('post.p_supprice',0,'strip_tags');

        if(!empty($p_color) && !empty($p_price) &&!empty($p_inventory) && !empty($p_supprice) )
        {
            $products=array();
            $i=0;
            foreach($p_price as $key=>$value)
            {
                $products[$i]['price']=$value;
                $products[$i]['color']=$p_color[$key];
                $products[$i]['inventory']=$p_inventory[$key];
                $products[$i]['supprice']=$p_supprice[$key];
                $products[$i]['productid']=$key;
                $i+=1;
            }
                //修改颜色、库存、价格
            $product=M('product');
            foreach($products as $key=>$value)
            {
                $product->itemid=$itemid;
                $product->inventory=$value['inventory'];
                $product->price=$value['price'];
                $product->color=$value['color'];
                $product->supprice=$value['supprice'];
                $temp_res=$product->where('productid=%d',$value['productid'])->save();

            }
        }

        //判断是否新增颜色，库存，价格
        $n_color=I('post.n_color','','strip_tags');
        $n_price=I('post.n_price',0,'strip_tags');
        $n_inventory=I('post.n_inventory',0,'strip_tags');
        $n_supprice=I('post.n_supprice',0,'strip_tags');
        if(!empty($n_price) && !empty($n_color) && !empty($n_inventory) && !empty($n_supprice))
        {
            $product=M('product');
            $product->create();
            foreach ($n_price as $key => $value)
            {
                $product->itemid=$itemid;
                $product->inventory=$n_inventory[$key];
                $product->price=$n_price[$key];
                $product->color=$n_color[$key];
                $product->supprice=$n_supprice[$key];
                $result=$product->add();
            }
        }
         //更新成功
        //$this->success('修改成功','index');
         //获取跳转页数
         $ipage=cookie('page');
         $ipage=!empty($ipage)?$ipage:1;
         $my_typeid=!empty($_COOKIE['typeid'])?$_COOKIE['typeid']:'';
         $my_brandid=!empty($_COOKIE['brandid'])?$_COOKIE['brandid']:'';
         $my_keywords=!empty($_COOKIE['keywords'])?base64_encode($_COOKIE['keywords']):'';
       //  $this->success('修改成功','index?page='.$ipage);
         $this->success('修改成功',U('index',array('page'=>$ipage,'typeid'=>$my_typeid,'brandid'=>$my_brandid,'keywords'=>$my_keywords),'' ) );
        
        


    }
    /*
       * 删除商品
       *@param itemid 商品id
     */
    public function delItem()
    {

        $itemid=I('get.itemid',0,'strip_tags');

        if (empty($itemid)) {
            echo  json_encode(array("status"=>0,"msg"=>"参数错误" ),JSON_UNESCAPED_UNICODE);
            return '';
        }

        $result=M('item')->where("itemid=%d",$itemid)->delete();

        if (!empty($result))
        {
            $item_desc=M('item_desc');
            $item_property=M('item_property');
            $product=M('product');
            $temres=$item_desc->where("itemid=%d",$itemid)->count();

            if(!empty($temres)) $item_desc->where("itemid=%d",$itemid)->delete();

            $temres=$item_property->where("itemid=%d",$itemid)->count();

            if(!empty($temres))   $item_property->where("itemid=%d",$itemid)->delete();

            $temres=$product->where("itemid=%d",$itemid)->count();

            if (!empty($temres))
            {
                $product->where("itemid=%d",$itemid)->delete();
            }

            echo json_encode(array("status"=>1,"msg"=>"删除成功"),JSON_UNESCAPED_UNICODE) ;

        }else
        {
            echo json_encode(array("status"=>0,"msg"=>"删除失败"),JSON_UNESCAPED_UNICODE) ;
        }



    }

    //公共方法
    public function cstrpos($haystack,$needle)
    {

        return strpos(strval($haystack),strval($needle)) !== false;

    }
//上传图片
    public function uploadimg(){
            //保存商品图片
        $config['path']=C('Admin_IMG_PATH');
        $config['maxwidth']=C('LIST_MAX_WIDTH');
        $config['maxheight']=C('LIST_MAX_HEIGHT');
         //判断是那个供应商上传的，重新定义图片路径
        if(!file_exists($config['path']))
        {
            mkdir( $config['path'], 0777 , true );

        }
        $config['maxsize']=C('IMG_MAX_SIZE');
        $img=imgUpload($config);
         //上传出错
        if(is_string($img)){
            return false;
        }
        $imginfo=$img['listimg'];
        if(!empty($imginfo['savename']))
        {
            $itemimg=substr(C('Admin_IMG_PATH'),1).$imginfo['savepath'].$imginfo['savename'];

        }

        return $itemimg;
    }
    //ajax  获取商品首页 类目、品牌、 是否上下架
    public function Type2Brand(){
        

        //获取所有类目
        $type=new \Home\Controller\TypeController();
        $typearr=$type->getListCat();
        //获取所有品牌
        $brands=M('brand')->order('brandid desc')->getField('brandid,brandname');
        $string="";
        foreach ($typearr as $key => $value)
        {
            
            
                $string.='<option value='.$key.' >'.str_repeat('&nbsp;&nbsp;&nbsp;',$value['level']).$value['typename'].'</option>';
            
        }
        

        $bsting='';
        foreach ($brands as $key => $value)
         {

                $bsting.='<option value='.$key.' >'.$value.'</option>';
        }
        $result['string']=$string;
        $result['bsting']=$bsting;
        echo json_encode($result,JSON_UNESCAPED_UNICODE);

    }
    /*
     *类目、品牌 通过ajax 联动
     */
    public function getBrand()
    {
        $typeid=I('get.typeid',0,'strip_tags');
        $brandid=!empty($_COOKIE['brandid'])?$_COOKIE['brandid']:0;
        //获取所有品牌
        $brands=M('brand a')->join('inner join '.C(DB_PREFIX).'type_brand b on a.brandid=b.brandid')
                ->where('b.typeid=%d',$typeid)->order('a.brandid desc')->getField('a.brandid,a.brandname');
        $bsting="<option value=0>选择品牌</option>";
        foreach ($brands as $key => $value)
         {
            if ($key==$brandid)
            {
                $bsting.='<option value='.$key.' selected >'.$value.'</option>';
            }else
            {
                $bsting.='<option value='.$key.' >'.$value.'</option>';
            }
        }
        echo json_encode($bsting,JSON_UNESCAPED_UNICODE);
    }

    /*
     *商品预览
     *@param Itemid 
     *
     */
    public function viewItem()
    {
        $itemid=I('get.itemid',0,'strip_tags');
        $result=M('item_desc')->where('itemid=%d',$itemid)->getField('itemdesc');
        $this->assign('itemdesc',$result);
        $this->display('preview');
    }
    //
    /*
     *ajax 检测商品Bn 是否唯一
     *retun json
     */
    public function ajaxBn(){
            $bn=I('get.bn','测试','strip_tags');
            $platid=!empty($_SESSION['adminid'])?$_SESSION['adminid']:0;//总后台ID
            $result=M('item')->where("bn='%s' And platid='%d'",$bn,$platid)->count();
            if(!empty($result)){
                echo json_encode(array('msg'=>'型号已添加','status'=>0),JSON_UNESCAPED_UNICODE);
            }else{
                echo json_encode(array('msg'=>'ok','status'=>1),JSON_UNESCAPED_UNICODE);
            }
            
            
    }
    /*
     * ajax 筛选商品
     * @param 
     * echo json
     */
    public function getItem(){
        $arg=array();
        $arg['typeid']=I('post.typeid',0,'strip_tags');
        $arg['typeid']=!empty($_POST['typeid'])?$_POST['typeid']:$_COOKIE['typeid'];
        $arg['brandid']=!empty($_POST['brandid'])?$_POST['brandid']:$_COOKIE['brandid'];
        $arg['keywords']=I('post.keywords','','strip_tags');
        $arg['page']=I('post.page',1,'strip_tags');
        $arg['platid']=I('post.platid',1,'strip_tags');
        $item=D('item');
        $result=$item->index($arg);

        if(!empty($result['item'])){
            $result['status']=1;
            $result['item']=array_values($result['item']);
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
            return '';

        }

        $result['status']=0;
        $result['message']='暂无数据';
        echo  json_encode($result,JSON_UNESCAPED_UNICODE);
    }



    /**
     * 检测品牌是否存在
     */
    public function ajaxbrand(){
        $where['brandname']=I('get.brand','','strip_tags');
        $id=M('brand')->where($where)->getField("brandid");
        if(empty($id))
        {
            $data = array('status'=>404,'code'=>'error','info'=>'该品牌不存在请先添加');
           echo json_encode($data);
        }else
        {
             $data = array('status'=>200,'code'=>'success','info'=>'允许添加');
           echo json_encode($data);

        }
    }


    /*
     *审核运营商上传的产品
     *@param itemid
     *return json
     */
    public function examineItem()
    {
        //获取orderid
        $itemid=I('get.itemid','','strip_tags');
        //判断 此商品是否为运营商产品而且为未审核状态
        $item=M('item');
		$result=$item->where('itemid=%d',$itemid)->getField('examine');
		$status=intval($result);
		if( $status ===0){
            //运营商的未审核产品
            $temp=array();
            //更新状态
            $temp=$item->where('itemid=%d',$itemid)->setField('examine',1);
            if ($temp !==false) 
            {
                $result1['status']=1;
                $result1['msg']='已审核';
                echo json_encode($result1 ,JSON_UNESCAPED_UNICODE);
                return '';
            }

            $result1['status']=0;
            $result1['msg']='系统繁忙,审核失败';
            echo json_encode($result1 ,JSON_UNESCAPED_UNICODE);
            return '';
            
        }

        $result1['status']=0;
        $result1['msg']='产品已审核';
        echo json_encode($result1 ,JSON_UNESCAPED_UNICODE);
        return '';
    }

    /*
     × 通过ajax 更改商品的上下架
     × @param itemid
     * return json
     */
     public function editStatus(){

        $result=array();
        $itemid=I('post.itemid',0,'strip_tags');
        $action=I('post.action','','strip_tags');

        //判断商品是否已审核
        $item=M('item');
        $item->create();
        $examine =$item->where('itemid=%d',$itemid)->getField('examine ');
        if(empty($examine))
        {
            //未审核
            $result['status']=0;
            $result['msg']='等待管理员审核';
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
            return '';
        }
        //已审核,判段是上架还是下架
        if($action=='up'){
            $item->status=1;
        }elseif ($action=='down'){
            $item->status=2;
        }


        $res=$item->where('itemid=%d',$itemid)->field('status')->save();
        if($res !== false)
        {   
            $result['status']=1;
            $result['action']=$action;
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
            return '';
        }

        $result['status']=0;
        $result['msg']='系统繁忙，请稍后再试';
        echo  json_encode($result,JSON_UNESCAPED_UNICODE);
        return '';
        
     }


     /*
      *ajax 修改价格，供货价，库存
      *@param itemid
      *@param action
      *@param value
      *return json
      */
     public function ajaxEditItem(){
        $action=I('post.action',0,'strip_tags');
        $itemid=I('post.itemid',0,'strip_tags');
        $spanval=I('post.spanval',0,'strip_tags');
        $spanval=intval($spanval);
        $where['itemid']=array('eq',intval($itemid)); 
        $item=M('item');
        
        $result=array();
        $status=false;
        switch ($action) 
        {
            //修改售价
            case 'price':
                if (empty($itemid)) break;
                $oldsupprice=$item->where("itemid=%d",$itemid)->getField('supperprice');
                if ($spanval < $oldsupprice ) {
                    $result['status']=0;
                    $result['msg']='零售价必须大于供货价';
                    echo json_encode($result,JSON_UNESCAPED_UNICODE);
                    return '';
                }
                
                $item->price=$spanval;
                $status=$item->where($where)->save();
                break;
            
            case 'supprice':
            if (empty($itemid)) break;
                $where['supperprice']=array('egt',0);
                $item->supperprice=$spanval;
                $status=$item->where($where)->save();
                if ($status === 0) 
                {
                    $result['status']=0;
                    $result['msg']='供货价必须大于0';
                    echo json_encode($result,JSON_UNESCAPED_UNICODE);
                    return '';

                }
                break;
            case 'inventory':
                if (empty($itemid)) break;
                $where['inventory']=array('egt',0);
                $item->inventory=$spanval;
                $status=$item->where($where)->save();  
                if ($status === 0) 
                {
                    $result['status']=0;
                    $result['msg']='库存必须大于0';
                    echo json_encode($result,JSON_UNESCAPED_UNICODE);
                    return '';

                }
                break;
        }
        if ($status !== false) 
        {
            $result['status']=1;
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
            return '';

        }
        $result['status']=0;
        $result['msg']='系统繁忙，请稍后再试！';
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
        return '';
     }
     /**
      * 获取二级类目
      */
     public function stype(){
        $where['pid']=$_GET['typeid'];
       $setype=M('type')->where($where)->getField('typeid,typename');
       $str='';
   foreach($setype as  $k=>$v){
    $str.= '<option value='.$k.'>'.$v.'</option>';

   }
  echo $str;
       


     }
     /**
      * 获取品牌
      */
     public function brand()
     {
        $where['a.typeid']=$_GET['brandid'];
        $brands=M('type_brand a')->join('cart_brand b on a.brandid=b.brandid')
                                ->where($where)
                                ->getField('b.brandid,b.brandname');
       foreach ($brands as $k=>$v)
       {
            $str.= '<option value='.$k.'>'.$v.'</option>';
       }
       echo $str;
     }

      /*
     *ajax 弹出货品规格（颜色，价格，库存，供应价）
     *@param itemid
     *@return json
     */
    public function ajaxProduct()
    {
        $itemid=I('post.itemid',0,'strip_tags');
        $item=M('item a');
        $products=$item->join('inner join '.C('DB_PREFIX').'product b on a.itemid=b.itemid')
                        ->where('a.itemid=%d',$itemid)
                        ->getField('b.productid,a.itemid,a.itemname,a.bn,b.price,b.color,b.supprice,b.inventory');
        $result=array();
        $result['status']=!empty($products)?1:0;
        $result['message']=empty($products)?'此产品没有规格':'';
        $result['products']=!empty($products)?array_values($products):'';

        echo json_encode($result);
    }

     /*
     ×ajax 直接修改货品价格，颜色，库存，供应价
     @param productid
     return json
     */
    public function ajaxEditproduct()
    {
        $result=array();
        $action=I('post.action','','strip_tags');
        $productid=I('post.productid',0,'strip_tags');
        $itemid=I('post.itemid',0,'strip_tags');
        $value=I('post.spanval','','strip_tags');
        if(empty($action) || empty($productid) || empty($value) )
            { 
                $result['status']=0;
                $result['message']='系统繁忙，请稍后再试！';
                echo json_encode($result);
                return '';
            }
        $product=M('product');
        $where['productid']=$productid;
        switch ($action) 
        {
            case 'prodcutcolor':
                //修改货品颜色
                $data['color']=$value;
                $temp=$product->where($where)->save($data);
                break;
            case 'prodcutprice':
                //修改货品价格
                $data['price']=$value;
                $temp=$product->where($where)->save($data);
                break;
            case 'prodcutsupprice':
                //修改货品供应价
                $data['supprice']=$value;
                $temp=$product->where($where)->save($data);
                break;
            case 'productinventory':
                //修改库存
                $data['inventory']=$value;
                $temp=$product->where($where)->save($data);
                break;
        }
        if (!empty($itemid))
        {
            //获取货品的库存和，更新基础库存
            $suminven =$product->where('itemid=%d',$itemid)->sum('inventory');

            $suminven=intval($suminven);
            $res=M('item')->where('itemid=%d',$itemid)->save(array('inventory'=>$suminven));
            if ($res !== false)
            {
                $result['itemid']=$itemid;
                $result['suminven']=$suminven;      
            }   
        }
        if($temp !==false)
        {
            $result['status']=1;
            echo json_encode($result);
            return '';
        }
        $result['status']=0;
        echo json_encode($result);
        return '';
        
    }

     
    

}
